#! /usr/local/bin/python

import sys
import os
import re

import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import parseaddr, formataddr

class Gmail_sender:
   """Class for sending mail via the GMail service"""
   def __init__(self):
      """Creates a new Gmail_sender object and asks for password"""
      sys.stdout.write("GMail password: ")
      self.password = sys.stdin.readline()
      self.password.strip()

   @classmethod
   def send_gmail_message(cls, login, password, from_addr, to_addr, subject, message_body):
      """Sends a message using the GMail service

      Parameters:
      login -- GMail login to use
      password -- GMail password to use
      from_addr -- The sender name and address to use
      to_addr -- The recipient's address
      subject -- The mail subject
      message_body -- The message content to send
      """
      # define addresses and credentials
      #   define charsets
      header_charset = 'ISO-8859-1'
      body_charset = 'UTF-8'
      try:
         message_body.encode(body_charset)
      except UnicodeError:
         print >> sys.stderr, "Gmail_sender: Error converting message into "+body_charset
         sys.exit(1)
      #
      #   define addresses and names
      (sender_name, sender_addr) = parseaddr(from_addr)
      (recipient_name, recipient_addr) = parseaddr(to_addr)
      #   ... names
      sender_name = str(Header(unicode(sender_name), header_charset))
      recipient_name = str(Header(unicode(recipient_name), header_charset))
      #   ... addresses
      sender_addr = sender_addr.encode('ascii')
      recipient_addr = recipient_addr.encode('ascii')
      #  
      #   compile the message
      msg = MIMEText(message_body.encode(body_charset), 'plain', body_charset)
      msg['From'] = formataddr((sender_name, sender_addr))
      msg['To'] = formataddr((recipient_name, recipient_addr))
      msg['Subject'] = Header(unicode(subject), header_charset)
      #
      # send to server
      server = smtplib.SMTP('smtp.gmail.com', 587)
      server.set_debuglevel(0)
      server.ehlo()
      server.starttls()
      server.login(login, password)
      server.sendmail(from_addr, to_addr, msg.as_string())
      server.quit()
      return

   def send_tutoring_message(self, to_addr, subject, message_body):
      """Sends a message using the tutoringisc GMail account
      (The password from the Gmail_sender object is used for authentication)

      Parameters:
      to_addr -- The recipient's address
      subject -- The mail subject
      message_body -- The message content to send
      """
      tutoring_from = "Tutoring ISC MU Brno <tutoringisc@gmail.com>"
      tutoring_login = "tutoringisc@gmail.com"
      tutoring_password = self.password
      Gmail_sender.send_gmail_message(tutoring_login, tutoring_password,\
                                      tutoring_from, to_addr,\
                                      subject, message_body)


